package com.xes.apps.ams.client.rd60n.jiecard.cn;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import com.xes.apps.ams.client.rd60n.jiecard.cn.NetConn;

public class UDPClientConn implements NetConn {
	private String dev_ip;
	private DatagramSocket conn;

	private int ConnectTo() {
		if (conn == null) {
			try {
				conn = new DatagramSocket();
				conn.setSoTimeout(5000);

			} catch (Exception e) {
				Close();
				e.printStackTrace();
			}
		}
		if (conn == null)
			return 1;
		else
			return 0;
	}

	public UDPClientConn(String ip) {
		dev_ip = ip;
		conn = null;
	}

	@Override
	public int SendData(byte[] data) {
		
		int result = 1;
		try {
			InetAddress addr = InetAddress.getByName(dev_ip);
			DatagramPacket packet = new DatagramPacket(data,data.length,new InetSocketAddress(addr, 8013));
			do {
				if (0 != ConnectTo())
					break;
				conn.send(packet);
				result = 0;
			} while (false);
		} catch (IOException e) {
			Close();
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public byte[] RecvData(int len) {
		byte[] data = null;
		if (0 != ConnectTo())
			return data;
		byte[] data_tmp = new byte[512];
		DatagramPacket packet = new DatagramPacket(data_tmp, data_tmp.length);

		try {
			conn.receive(packet);
			data = new byte[packet.getLength()];
			for (int i = 0; i < data.length; ++i) {
				data[i] = data_tmp[i];
			}
			data_tmp = null;

		} catch (IOException e) {
			data = null;
			Close();
			e.printStackTrace();
		}

		return data;
	}

	@Override
	public String ConnIpAddr() {
		if (null != conn) {
			return conn.getInetAddress().getHostName();
		}
		return "";
	}

	@Override
	public int ConnPort() {
		if (null != conn) {
			return conn.getPort();
		}
		return 0;
	}

	@Override
	public int Close() {
		int result = 1;
		if (null != conn) {
			try {
				conn.close();
				conn = null;
				result = 0;
			} catch (Exception e) {
				conn = null;
				e.printStackTrace();
			}
		}
		return result;
	}
}
